package com.ibm.cps.sql.expression.json;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ibm.cps.sql.expression.FunctionNode;
import com.ibm.cps.sql.expression.ValueExpression;

public class FunctionNodeDeserializer extends JsonDeserializer<FunctionNode>{

	@Override
	public FunctionNode deserialize(JsonParser jp, DeserializationContext ctxt)
			throws IOException, JsonProcessingException {
		try {
			ObjectMapper mapper = (ObjectMapper) jp.getCodec();  
			ObjectNode root = (ObjectNode) mapper.readTree(jp);
			String functionName = root.get("functionName").asText();
			ArrayNode argTypes = (ArrayNode)root.get("argTypes");
			ArrayNode args = (ArrayNode)root.get("arguments");
			ValueExpression[] arguments = new ValueExpression[argTypes.size()];
			for (int i = 0; i < arguments.length; i++) {
				String type = argTypes.get(i).asText();
				String json = args.get(i).toString();
				arguments[i] = (ValueExpression)mapper.readValue(json, Class.forName(type));
			}
			System.out.println("inside calc deserializer: " + root);
			return new FunctionNode(functionName, arguments);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			throw new IllegalArgumentException(e);
		}
	}

}
